<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { labelEnableList, useAreaList, useFlashAddOrUpdate, useFlashShow } from '@fl/api/advertising-api/flash-management'
import { getHouseList } from '@fl/api/xf-api/label-manage'
import { SubmitBtn } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { Editor } from '@fl/origin-components/Editor/index'
import { formatTime } from '@fl/utils'
import { cloneDeep } from 'lodash-es'

import { useDicts } from '../hooks/use-dicts'

const props = withDefaults(defineProps<{
    areaDict?: any
    sortDict?: any
    sortOptions?: any
}>(), {
    sortDict: [],
    sortOptions: [],
})

const emit = defineEmits(['query'])

const editorRef = ref(null)

const { dicts: { IsOrNot, OpenOrClose, OriginalType } } = useDicts()

const { areaDict, sortDict, sortOptions } = toRefs(props)

const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })
const formRef = ref()
const title = ref<string>('添加土拍政策')
const houseOptions = ref<any>([])
const classifyId = ref<string>('')
const labelOptions = ref<any>()
const labelDict = ref<any>()
const detailLabelsList = ref<any>([])
const scanVisible = ref<boolean>(false)
const scanTitle = ref<string>('土拍政策预览')

const initialState = {
    adFloorOne: '', // 楼盘
    adFloorTwo: '',
    areaCode: '',
    areaName: '',
    choiceFlag: '0', // 是否精选：0-非精选 1-精选
    classifyId: '', // 分类id
    commentFlag: '0', // 开启评论：0-关闭 1-开启
    content: '', // 内容
    createBy: '', // 发布者
    createTime: '',
    hotFlag: '0', // 是否热点
    informationSources: '', // 来源
    labels: [], // 标签id集合
    newsTitle: '', // 标题
    newsTypeId: '2', // 业务类型id(1-安居快讯 2-土拍政策 3-保租房公告)
    originalFlag: '0', // 是否原创：0-非原创 1-原创
    titleImage: '', // 图片
    topFlag: '0', // 是否置顶
    urlAddress: '', // 链接地址
}
const state = ref(cloneDeep(initialState))

function getLabelEnableList(id: string) {
    const params = {
        classifyId: id,
    }
    labelEnableList(params).then((res: any) => {
        labelOptions.value = res.reduce((pre, cur) => {
            cur.value = cur.id
            cur.label = cur.labelName
            pre.push(cur)
            return pre
        }, [])
        labelDict.value = labelOptions.value.reduce((accumulator, current) => {
            accumulator[current.value] = current.label
            return accumulator
        }, [])
        // 处理详情标签回显
        if (detailLabelsList.value) {
            state.value.labels = detailLabelsList.value.reduce((pre: any, cur: any) => {
                labelOptions.value.forEach((item) => {
                    if (item.value === cur.id) {
                        pre.push(cur.id)
                    }
                })
                return pre
            }, [])
        }
        else {
            state.value.labels = []
        }

        classifyId.value = '' // 清空
    })
}

// 详情
const { data: detail, isLoading } = useFlashShow(id)
watchEffect(() => {
    if (detail.value) {
        title.value = '编辑土拍政策'
        state.value = cloneDeep(detail.value)

        // 分类
        state.value.classifyId = sortOptions.value.reduce((pre: any, cur: any) => {
            if (cur.value === detail.value.classifyId) {
                pre = cur.id
            }
            return pre
        }, '')

        // 根据分类id查标签列表
        classifyId.value = detail.value.classifyId
        detailLabelsList.value = detail.value.labelsList // 暂存

        state.value.originalFlag = detail.value.originalFlag
        state.value.choiceFlag = detail.value.choiceFlag
    }
    else {
        title.value = '添加土拍政策'
    }
})

watchEffect(() => {
    if (classifyId.value) {
        // console.log('watch', classifyId.value)
        getLabelEnableList(classifyId.value)
    }
})

// 所有楼盘
async function getHouseOptions() {
    await new Promise((resolve) => {
        getHouseList({ pageNum: 1, pageSize: 500, projectName: '' }).then((res) => {
            houseOptions.value = res.rows.reduce((pre: any, cur: any) => {
                cur.value = cur.projectId
                cur.label = cur.projectName
                pre.push(cur)
                return pre
            }, [])
            resolve('')
        })
    })
}
getHouseOptions()

// 去预览
function gotoScan() {
    scanVisible.value = true
}

// 提交表单
const { isPending, mutate } = useFlashAddOrUpdate()

// 提交
async function submit(type) {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        // 草稿：draftFlag为0
        // 正文：draftFlag为1，delFlag为1
        // 类别：newsTypeId 业务类型（1-安居快讯 2-土拍政策 3-保租房公告,4-土地推介)
        const params = {
            id: id.value ?? '',
            ...unref(state),
            areaCode: state.value.areaCode ? state.value.areaCode : '',
            areaName: state.value.areaCode ? areaDict.value[state.value.areaCode] : '',
            createTime: formatTime(state.value.createTime, 'yyyy-MM-dd HH:mm:ss'),
            delFlag: 1,
            draftFlag: type,
            labels: cloneDeep(state.value.labels),
            newsTypeId: state.value.newsTypeId,
            // 后端需求：为空时给任意过去的时间
            topEndTime: formatTime(state.value.topTime?.[1], 'yyyy-MM-dd 23:59:59') || '1970-12-01 00:00:00',
            topStartTime: formatTime(state.value.topTime?.[0], 'yyyy-MM-dd 00:00:00') || '1970-12-30 00:00:00',
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

// 分类切换，查询标签
function classifyChange(val) {
    // console.log('classifyChange', classifyId.value)
    classifyId.value = val
    state.value.labels = [] // 清空标签
}

function urlChange() {
    formRef.value.formInstance.clearValidate('titleImage')
}

function cancel() {
    emit('query', '')
    reset()
}

// newsTypeId 业务类型（1-安居快讯 2-土拍政策 3-保租房公告,4-土地推介)
const typeOptions = ref([
    { label: '土拍政策', value: '2' },
    { label: '土地推介', value: '4' },
])

function reset() {
    id.value = ''
    state.value = cloneDeep(initialState)
    visible.value = false
    formRef.value.formInstance.resetFields()
    state.value.content = ''
    scanCancel()
}

function scanCancel() {
    scanVisible.value = false
}

const districtTypes = ref([])
// 分类、标签列表
const { data: areaDataList } = useAreaList()
watchEffect(() => {
    if (areaDataList.value) {
        const rows = cloneDeep(areaDataList.value)
        const cityList = rows.data
	    const targetCity = cityList.find((item) => {
            return item.areaName == '武汉市'
        })
        districtTypes.value = targetCity.children
        districtTypes.value.map((it) => {
            it.value = it.areaCode
            it.label = it.areaName
            return it
        })
    }
})

const columns: PlusColumn[] = [
    {
        colProps: { span: 22 },
        fieldProps: {
            maxlength: 50,
            showWordLimit: true,
        },
        label: '标题',
        prop: 'newsTitle',
    },
    {
        colProps: { span: 12 },
        label: '所属区域',
        options: computed(() => {
            return districtTypes.value
        }),
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        label: '业务类型',
        prop: 'newsTypeId',
        valueType: 'select',
        options: computed(() => {
            return typeOptions.value
        }),
    },
    {
        colProps: { span: 22 },
        fieldProps: {
            type: 'datetime',
        },
        label: '定时发布时间',
        prop: 'createTime',
        valueType: 'date-picker',
    },
    /* {
        colProps: { span: 12 },
        label: '评论功能',
        prop: 'commentFlag',
    },
    {
        colProps: { span: 12 },
        label: '是否置顶',
        prop: 'topFlag',
    },
    {
        colProps: { span: 22 },
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        hideInForm: computed(() => state.value.topFlag === '0'),
        label: '置顶时间',
        prop: 'topTime',
        valueType: 'date-picker',
    }, */
    {
        label: '图片',
        prop: 'titleImage',
    },
    {
        colProps: { span: 22 },
        fieldProps: {
            maxlength: 20,
            showWordLimit: true,
        },
        label: '发布者',
        prop: 'createBy',
    },
    /**
         {
        label: '是否原创',
        prop: 'originalFlag',
    },
    {
        colProps: { span: 22 },
        hideInForm: computed(() => state.value.originalFlag === '1'),
        label: '链接地址',
        prop: 'urlAddress',
    },
    */
    {
        colProps: { span: 22 },
        label: '内容',
        prop: 'content',
    },
    /**
         {
        colProps: { span: 22 },
        fieldProps: {
            filterable: true,
        },
        label: '广告楼盘',
        options: computed(() => {
            return houseOptions.value
        }),
        prop: 'adFloorOne',
        valueType: 'select',
    },
    {
        colProps: { span: 22 },
        fieldProps: {
            filterable: true,
        },
        label: '广告楼盘',
        options: computed(() => {
            return houseOptions.value
        }),
        prop: 'adFloorTwo',
        valueType: 'select',
    },*
    */
]

const rules = {
    choiceFlag: [
        {
            required: true,
        },
    ],
    newsTypeId: [
        {
            message: '请选择业务类型',
            required: true,
        },
    ],
    commentFlag: [
        {
            required: true,
        },
    ],
    content: [
        {
            message: '请填写快讯内容',
            required: true,
        },
    ],
    createBy: [
        {
            message: '请填写发布者，20字以内',
            required: true,
        },
    ],
    createTime: [
        {
            message: '请选择发布时间',
            required: true,
        },
    ],
    newsTitle: [
        {
            message: '请输入标题，50字以内',
            required: true,
        },
    ],
    originalFlag: [
        {
            required: true,
        },
    ],
    titleImage: [
        {
            message: '请上传图片',
            required: true,
        },
    ],
    topFlag: [
        {
            required: true,
        },
    ],
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                :has-footer="true"
                :fullscreen="true"
                class="custom-dialog"
                style="overflow:hidden"
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="plusform mt-20">
                <PlusForm ref="formRef"
                          v-model="state"
                          :columns="columns"
                          :label-width="120"
                          :rules="rules"
                          :has-footer="false"
                          :row-props="{ gutter: 20 }"
                >
                    <template #plus-field-topFlag>
                        <el-radio-group v-model="state.topFlag">
                            <el-radio v-for="(item, index) in IsOrNot"
                                      :key="index"
                                      :label="item.label"
                                      :value="item.value"
                            />
                        </el-radio-group>
                    </template>

                    <template #plus-field-hotFlag>
                        <el-radio-group v-model="state.hotFlag">
                            <el-radio v-for="(item, index) in IsOrNot"
                                      :key="index"
                                      :label="item.label"
                                      :value="item.value"
                            />
                        </el-radio-group>
                    </template>

                    <template #plus-field-choiceFlag>
                        <el-radio-group v-model="state.choiceFlag">
                            <el-radio v-for="(item, index) in IsOrNot"
                                      :key="index"
                                      :label="item.label"
                                      :value="item.value"
                            />
                        </el-radio-group>
                    </template>

                    <template #plus-field-commentFlag>
                        <el-radio-group v-model="state.commentFlag">
                            <el-radio v-for="(item, index) in OpenOrClose"
                                      :key="index"
                                      :label="item.label"
                                      :value="item.value"
                            />
                        </el-radio-group>
                    </template>

                    <template #plus-field-classifyId>
                        <el-select v-model="state.classifyId"
                                   @change="classifyChange"
                        >
                            <el-option v-for="item in sortOptions"
                                       :key="item.value"
                                       :value="item.value"
                                       :label="item.label"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-titleImage>
                        <FlUpload :key="String(id)"
                                  v-model="state.titleImage"
                                  @success="urlChange"
                        />
                    </template>

                    <template #plus-field-originalFlag>
                        <el-radio-group v-model="state.originalFlag">
                            <el-radio v-for="(item, index) in OriginalType"
                                      :key="index"
                                      :label="item.label"
                                      :value="item.value"
                            />
                        </el-radio-group>
                    </template>

                    <template #plus-field-content>
                        <Editor v-if="visible"
                                ref="editorRef"
                                v-model="state.content"
                                :is-jc-mall="false"
                        />
                    </template>
                </plusform>
            </div>
        </template>

        <template #footer>
            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           plain
                           :loading="isPending"
                           @click="submit(0)"
                >
                    保存
                </SubmitBtn>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="gotoScan"
                >
                    预览并发布
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>

    <!-- 预览 -->
    <PlusDialog v-model="scanVisible"
                :title="scanTitle"
                width="400"
                close-on-press-escape
                :has-footer="false"
                style="padding:40px 0 0 0!important;"
                @cancel="scanCancel"
                @closed="scanCancel"
    >
        <div class="content">
            <div class="title">
                {{ state.newsTitle }}
            </div>

            <div class="flex">
                <div class="create">
                    {{ state.createBy }}
                </div>

                <div class="time">
                    {{ formatTime(state.createTime, 'yyyy-MM-dd HH:mm:ss') }}
                </div>
            </div>

            <div class="flex">
                <ElTag v-for="(item, index) in state.labels"
                       :key="index"
                       type="success"
                       class="mb5 mr10 mt5"
                >
                    {{ labelDict[item] }}
                </ElTag>
            </div>

            <div class="detail">
                <div v-html="state.content" />
            </div>
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="scanCancel">
                取消预览
            </el-button>

            <SubmitBtn type="primary"
                       :loading="isPending"
                       @click="submit(1)"
            >
                发布
            </SubmitBtn>
        </div>
    </PlusDialog>
</template>

<style lang="scss" scoped>
.plusform {
    height: 74vh;
    overflow: hidden auto;
}

:deep(.el-col:last-child .el-form-item__label) {
    opacity: 0;
}

.content {
    min-height: 560px;
    overflow: hidden auto;
    .title {
        font-size: 18px;
        font-weight: 600;
    }
    .create {
        font-size: 14px;
        font-weight: 500;
    }
    .time {
        font-size: 14px;
        color: #bbb;
        margin-left: 20px;
        width: 200px;
    }
    .detail {
        margin-top: 8px;
    }
}
</style>
